package com.base.myproject.client.ui;

import com.base.myproject.client.busi.MenuCommandFactory;
import com.base.myproject.client.busi.TestBusi;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.system.GetBaseResource;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.menu.CheckMenuItem;
import com.extjs.gxt.ui.client.widget.menu.Menu;
import com.extjs.gxt.ui.client.widget.menu.MenuItem;
import com.extjs.gxt.ui.client.widget.menu.SeparatorMenuItem;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;

/**
 * @author admin 小陈修改了让菜单可以显示分格线
 * 
 */
public class BaseMenuBar extends ToolBar {
	static BaseMenuBar basemenubar = null;

	private BaseMenuBar() {

	}

	public static BaseMenuBar getinstance() {
		if (basemenubar == null) {
			basemenubar = new BaseMenuBar();

			basemenubar.setBorders(false);

		}
		try {
			String path = com.google.gwt.user.client.Window.Location.getPath();

			basemenubar.sendServlet("Loadmenu", "gwtbase/BaseServlet",
					"Action=loadmenu&menu1=13&system=" + path);

		} catch (RequestException e) {
			e.printStackTrace();
		}

		return basemenubar;
	}

	public void addItem(Component item) {

		basemenubar.add(item);

	}

	public void removeItem(Component item) {

		basemenubar.remove(item);
	}

	public void _add() {
		Button item1 = new Button("Button w/ Menu");
		item1.setIconStyle("icon-menu-show");
		Menu menu = new Menu();
		CheckMenuItem menuItem = new CheckMenuItem("I Like Cats");
		menuItem.setChecked(true);
		menu.add(menuItem);

		menuItem = new CheckMenuItem("I Like Dogs");
		menu.add(menuItem);
		item1.setMenu(menu);

		MenuItem menuitem2 = new MenuItem();
		menuitem2.setText("menuitem2");
		menuitem2.addSelectionListener(new SelectionListener() {

			@Override
			public void componentSelected(ComponentEvent ce) {

			}

			public void handleEvent(BaseEvent be) {
				HTML homeText = new HTML("Tab you have selected is Home.");
				BaseTabPanel.getInstance().addTab("zgw4", new TestBusi());

			}
		});

		menu.add(menuitem2);

		basemenubar.add(item1);
	}

	/**
	 * 从服务器上取得菜单
	 * 
	 * @param servletflag
	 * @param url
	 * @param form
	 * @return
	 * @throws RequestException
	 */
	public boolean sendServlet(String servletflag, String url, String form)
			throws RequestException {
		RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL
				.encode(url));
		builder.setHeader("Content-Type",
				"application/x-www-form-urlencoded;charset=utf-8");
		if (Env.getUid() != null)
			form += "&system_uuid=" + Env.getUid();

		builder.sendRequest(form, new RequestCallback() {

			@Override
			public void onError(Request request, Throwable exception) {
				System.out.println(" send servlet error");
				Window.alert("send servlet error");
			}

			@Override
			public void onResponseReceived(Request request, Response response) {
				String xmlstr = response.getText();
				Document customerDom = XMLParser.parse(xmlstr);
				Element customerElement = customerDom.getDocumentElement();
				XMLParser.removeWhitespace(customerElement);
				NodeList nl = customerElement.getElementsByTagName("record");

				setMenu(nl);

//				if (Env.getEnvname() != null) {
//					basemenubar.add(new SeparatorToolItem());
//					Html html = new Html(" 登录人员：" + Env.getEnvname());
//					html.setStyleAttribute("font-size", "12px");
//					basemenubar.add(html);
//
//				}
			}

			java.util.HashMap<String, Object> menuhm = new java.util.HashMap<String, Object>();

			/**
			 * 从服务器上获得 str +="<records>"; str +="<record>"; str
			 * +="<menucode>1001</menucode><menuname>menu1</menuname>"; str
			 * +="</record>"; str +="</records>";
			 * xml文件，通过menucode的长度，编辑4位一级，每4位为下一级菜单。注意：要想对编号进行排序
			 * 
			 * @param nl
			 */
			public void setMenu(NodeList nl) {

				for (int i = 0; i < nl.getLength(); i++) {
					Element e = (Element) nl.item(i);
					String code = "";
					String name = "";
					String cssstyle = "";
					String command = null;

					for (int j = 0; j < e.getChildNodes().getLength(); j++) {
						Element e2 = (Element) nl.item(i).getChildNodes().item(
								j);

						if (e2.getNodeName().equals("menucode")) {
							if ((e2.getFirstChild() != null)
									&& (e2.getFirstChild().getNodeValue() != null))
								code = e2.getFirstChild().getNodeValue();
						} else if (e2.getNodeName().equals("menuname")) {
							if ((e2.getFirstChild() != null)
									&& (e2.getFirstChild().getNodeValue() != null))
								name = e2.getFirstChild().getNodeValue();
						} else if (e2.getNodeName().equals("cssstyle")) {
							if ((e2.getFirstChild() != null)
									&& (e2.getFirstChild().getNodeValue() != null))
								cssstyle = e2.getFirstChild().getNodeValue();
						} else if (e2.getNodeName().equals("command")) {
							if ((e2.getFirstChild() != null)
									&& (e2.getFirstChild().getNodeValue() != null))
								command = e2.getFirstChild().getNodeValue();

						}

					}

					if (name.equals("-")) {
						SeparatorMenuItem sItem = new SeparatorMenuItem();
						if (menuhm.get(code.length() / 4 - 1 + "") instanceof Menu) {
							((Menu) menuhm.get(code.length() / 4 - 1 + ""))
									.add(sItem);
							menuhm.put(code.length() / 4 + "", sItem);
						} else if (menuhm.get(code.length() / 4 - 1 + "") instanceof MenuItem) {
							((MenuItem) menuhm.get(code.length() / 4 - 1 + ""))
									.getSubMenu().add(sItem);
							menuhm.put(code.length() / 4 + "", sItem);
						}
						continue;
					}

					if (code.length() / 4 == 1) {
						Button tti = new Button(name);
						tti.setIcon(AbstractImagePrototype
								.create(GetBaseResource.getInstance()
										.getImageResource(cssstyle)));
						basemenubar.add(tti);
						Menu menu = new Menu();
						tti.setMenu(menu);
						menuhm.put(code.length() / 4 + "", menu);
					} else {
						MenuItem item = new MenuItem(name);

						if (command != null) {
							MenuCommandFactory mcf = new MenuCommandFactory(
									command);
							mcf.setDispalyname(name);
							item.addSelectionListener(mcf);
						}

						if (menuhm.get(code.length() / 4 - 1 + "") instanceof Menu) {

							((Menu) menuhm.get(code.length() / 4 - 1 + ""))
									.add(item);
							menuhm.put(code.length() / 4 + "", item);
						} else if (menuhm.get(code.length() / 4 - 1 + "") instanceof MenuItem) {

							if (((MenuItem) menuhm.get(code.length() / 4 - 1
									+ "")).getSubMenu() != null) {
								((MenuItem) menuhm.get(code.length() / 4 - 1
										+ "")).getSubMenu().add(item);
								menuhm.put(code.length() / 4 + "", item);
							} else {
								Menu menu = new Menu();
								menu.add(item);

								((MenuItem) menuhm.get(code.length() / 4 - 1
										+ "")).setSubMenu(menu);
								menuhm.put(code.length() / 4 + "", item);

							}

						}

					}

				}
			}

			public void setmenufromxml(NodeList nl, Button menuobject, Menu menu) {

				for (int i = 0; i < nl.getLength(); i++) {
					Element e = (Element) nl.item(i);
					if (e.getAttribute("type") != null)
						if (e.getAttribute("type").equals("tooltextitem")) {
							Button ttl = new Button(e
									.getAttribute("texttoolitemname"));
							{
								basemenubar.add(ttl);
							}

							if (e.hasChildNodes()) {
								setmenufromxml(e.getChildNodes(), ttl, null);
							}

						} else if (e.getAttribute("type").equals("menu")) {
							Menu menutemp = new Menu();
							menuobject.setMenu(menutemp);

							if (e.hasChildNodes()) {
								setmenufromxml(e.getChildNodes(), menuobject,
										menutemp);
							}

						} else if (e.getAttribute("type").equals("menuitem")) {
							MenuItem menuitem = new MenuItem();
							menuitem.setText(e.getAttribute("name"));
							menu.add(menuitem);

							menuitem
									.addSelectionListener(new SelectionListener() {

										@Override
										public void componentSelected(
												ComponentEvent ce) {
										}

										public void handleEvent(BaseEvent be) {
											try {
												BaseJDBCPanel bjp = GWT
														.create(com.base.myproject.client.busi.TestBusi2.class);
												BaseTabPanel.getInstance()
														.addTab("zgw4", bjp);

											} catch (Exception e) {
												e.printStackTrace();
											}

										}
									});
						}
				}
			}

		});

		return true;
	}
}
